package com.zhiqianbao.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.creditx.xbehavior.sdk.CreditXAgent;
import com.creditx.xbehavior.sdk.LoginMethod;
import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.activity.MainActivity;
import com.zhiqianbao.entity.CreditRating;
import com.zhiqianbao.entity.OprateState;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.User;
import com.zhiqianbao.entity.UserBank;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.entity.UserJob;
import com.zhiqianbao.listener.MyLocationListener;
import com.zhiqianbao.shared.SharedPreferanceUtils;

import java.util.HashMap;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liudehong on 2017/11/30.
 */
public class WorthPurseUtil {
    private Activity zhiddActivity;
    private Gson gson = new Gson();
    private Dialog waitDialog;
    private String errorMsg = "";
    private Map<String, String> systemInof;
    private String imei = "";
    private String imsi = "";
    private SharedPreferanceUtils sharedPreferanceUtils;
    private static WorthPurseUtil worthPurseUtil;

    public static void init() {
        //判断不为空跳过，省去synchronized判断操作，为空时需要对对象加锁排队处理
        if (worthPurseUtil == null) {
            synchronized (WorthPurseUtil.class) {
                if (worthPurseUtil == null) {
                    worthPurseUtil = new WorthPurseUtil();
                }
            }
        }
    }

    public static Activity getZhiddActivity() {
        return worthPurseUtil.zhiddActivity;
    }

    public static void loginWorthPurse(Activity activity, String zUserId) {
        worthPurseUtil.loginRegister(activity, zUserId);
    }

    public void loginRegister(Activity activity, String zUserId) {
        zhiddActivity = activity;
        sharedPreferanceUtils = new SharedPreferanceUtils(zhiddActivity.getApplicationContext());
        if (zhiddActivity != null) {
            Map<String, String> params = getParames();
            new LoginRegisterTask().execute(params);
        }
    }

    private class LoginRegisterTask extends AsyncTask<Map, Void, Result<HashMap>> {
        @Override
        protected Result<HashMap> doInBackground(Map... params) {
            //请求登录接口
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/loginNew",
                    params[0], zhiddActivity);

            if (StringUtils.isBlank(result)) {
                return null;
            }
            Result<HashMap> resultObject = Result.fromJson(result, HashMap.class);
            return resultObject;
        }

        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }

        @Override
        protected void onPostExecute(Result<HashMap> result) {
            if (result == null) {
//                CreditXAgent.onSubmit(ActionName.Submit.LOGIN,
//                        CreditXAgent.ActionStatus.FAILED,"登录失败");
                zhiddActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(zhiddActivity, "连接超时", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {

                //请求成功
                if (Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
//                    CreditXAgent.onSubmit(ActionName.Submit.LOGIN,
//                            CreditXAgent.ActionStatus.SUCCESS,"登录成功");
                    HashMap<String, Object> data = result.getData();
                    double countNoRepay = 0;
                    try {
                        countNoRepay = (double) data.get("countNoRepay");
                    } catch (Exception e) {

                    }
                    User loginUser = gson.fromJson(gson.toJson(data.get("user")), User.class);
                    if (loginUser != null) {
                        CreditXAgent.onUserLoginSuccess(LoginMethod.PASSWORD,
                                String.valueOf(loginUser.getId()));
                        String token_login = loginUser.getToken();
                        Long user_id = loginUser.getId();
                        Constants.LOGIN_USER = loginUser;
                        //将当前登陆用户保存到sqllite
                        User.deleteAll(User.class);
                        loginUser.save();
                        SharedPreferanceUtils.setUserId(String.valueOf(user_id));
                        SharedPreferanceUtils.setToken(token_login);
                        //登录姓名
                        String name = loginUser.getName();
                        String phone = loginUser.getPhone();
                        sharedPreferanceUtils.setUserName(name);
                        sharedPreferanceUtils.setPhoneNuber(phone);

                        //工作信息
                        String jobState = loginUser.getJobState();
                        //紧急联系人
                        String emergencyContactState = loginUser.getEmergencyContactState();
                        //身份证状态
                        String identityState = loginUser.getIdentityState();
                        //运营商
                        String telecomState = loginUser.getTelecomState();
                        //淘宝状态
//                        String taobaoState = loginUser.getTaobaoState();
                        sharedPreferanceUtils.setJobState(jobState);
                        sharedPreferanceUtils.seteEmergency(emergencyContactState);
                        sharedPreferanceUtils.setidCardState(identityState);
//                        sharedPreferanceUtils.setTaoBao(taobaoState);
                        sharedPreferanceUtils.setTelecon(telecomState);
                    }
                    try {
                        UserInfo userInfo = gson.fromJson(gson.toJson(data.get("userInfo")), UserInfo.class);
                        String name = userInfo.getName();
                        sharedPreferanceUtils.setName(name);
                        UserBank userBank = gson.fromJson(gson.toJson(data.get("userBank")), UserBank.class);
                        UserJob userJob = gson.fromJson(gson.toJson(data.get("userJob")), UserJob.class);
                        OprateState OprateState = gson.fromJson(gson.toJson(data.get("openStates")), OprateState.class);
//                    1：开启 0：未开启（以下几个状态一样）
                        //支付宝开启状态
                        String aliPayStatus = OprateState.getAliPayStatus();
                        //连连开启状态
                        String lianlianPayStatus = OprateState.getLianlianPayStatus();
                        //融宝开启状态
                        String rongbaoPayStatus = OprateState.getRongbaoPayStatus();
                        //芝麻开启状态
                        String zhimaStatus = OprateState.getZhimaStatus();
                        sharedPreferanceUtils.setZhimaOpenOrClose(zhimaStatus);
                        sharedPreferanceUtils.setLianlianPayStatus(lianlianPayStatus);
                        sharedPreferanceUtils.setRongbaoPayStatus(rongbaoPayStatus);
                        sharedPreferanceUtils.setAliPayStatus(aliPayStatus);

                        //
                        if (userJob != null) {
                            try {
                                String phone = userJob.getPhone();
                                String province = userJob.getProvince();
                                //市
                                String city = userJob.getCity();
                                //区
                                String address1 = userJob.getAddress();
                                String jobName = userJob.getJobName();
                                String company = userJob.getCompany();
                                String area = userJob.getArea();
                                //保存选择工作编号
                                String jobNmuber = userJob.getJob();

                                /**
                                 * 工作信息
                                 */
                                sharedPreferanceUtils.setAdress(city + address1);
                                sharedPreferanceUtils.setCompaney(company);
                                sharedPreferanceUtils.setJobNumber(jobNmuber);
                                sharedPreferanceUtils.setJob(jobName);
                                sharedPreferanceUtils.setProvince(province);
                                sharedPreferanceUtils.setArea1(area);
                                sharedPreferanceUtils.setCity12(city);
                                sharedPreferanceUtils.setCity(city + userBank.getProvince());
                                sharedPreferanceUtils.setPhone(phone);

                                UserJob.deleteAll(UserJob.class);
                                userJob.save();
                                String profession = userJob.getProfession();
                                String childProfession = userJob.getChildProfession();
                                if ((!TextUtils.isEmpty(profession)) && (!TextUtils.isEmpty(childProfession))) {
                                    sharedPreferanceUtils.setUserJobProfession(profession + "-" + childProfession);
                                } else {
                                    sharedPreferanceUtils.setUserJobProfession("");
                                }
                            } catch (Exception e) {

                            }

                        }
                        /**下面是银行卡信息**/
                        if (userBank != null) {
                            //卡号
                            String bankCard = userBank.getBankCard();
                            sharedPreferanceUtils.setBacnNumber(bankCard);
                            //所属银行
                            String deposit = userBank.getDeposit();
                            sharedPreferanceUtils.setBanckName(deposit);
                            //所在城市
                            String city1 = userBank.getCity() + userBank.getArea();
                            sharedPreferanceUtils.setCity(city1);

                            UserBank.deleteAll(UserBank.class);
                            userBank.save();
                        }

                        if (userInfo != null) {
                            //身份证号
                            String idcard = userInfo.getIdcard();
                            sharedPreferanceUtils.setidCard(idcard);

                            UserInfo.deleteAll(UserInfo.class);
                            userInfo.save();
                        }
                    } catch (Exception e) {

                    }

                    CreditRating creditRating = gson.fromJson(gson.toJson(data.get("creditRating")), CreditRating.class);
                    if (null != creditRating) {
                        CreditRating.deleteAll(CreditRating.class);
                        creditRating.save();
                    }
                    //开启推送
                    startPush();
                    //获取位置信息com.orm.util
                    location();
                    //上传设备信息
                    uploadUserDevice();
//                    postDataToServer();
                    if (countNoRepay != 0) {
                        Intent intent = new Intent(zhiddActivity, MainActivity.class);
                        intent.putExtra("tabPosition", 2);
                        zhiddActivity.startActivity(intent);
                    } else {
                        Intent intent = new Intent(zhiddActivity, MainActivity.class);
                        intent.putExtra("tabPosition", 1);
                        zhiddActivity.startActivity(intent);
                    }

                } else {
//                    CreditXAgent.onSubmit(ActionName.Submit.LOGIN,
//                            CreditXAgent.ActionStatus.FAILED,result.getMsg());
                    errorMsg = result.getMsg();
                    zhiddActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(zhiddActivity, errorMsg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
            closeWaitDialog();
        }
    }

    // 异步任务，自动登录功能
    private Map<String, String> getParames() {
        Message message = new Message();
        systemInof = SystemUtils.getSystemInfo(zhiddActivity);
        String phoneBrand = "";
        String phoneModel = "";
        String osVersion = "";
        if (systemInof != null) {
            imei = systemInof.get("imei");
            imsi = systemInof.get("imsi");
            phoneBrand = systemInof.get("manufacturer");
            phoneModel = systemInof.get("model");
            osVersion = systemInof.get("osVersion");
        }
        Map<String, String> registParam = new HashMap<>();
        registParam.put("phone", "13810676760");
        registParam.put("imei", imei == null ? "" : imei);
        registParam.put("imsi", imsi == null ? "" : imsi);
        registParam.put("phoneBrand", phoneBrand == null ? "" : phoneBrand);
        registParam.put("phoneModel", phoneModel == null ? "" : phoneModel);
        registParam.put("phoneOs", "Android " + (osVersion == null ? "" : osVersion));
        registParam.put("zUserId", "100100");
        return registParam;
    }

    /**
     * 推送创建
     */
    private void startPush() {
        String pkgName = Constants.MY_PKG_NAME;
        PushManager.startWork(zhiddActivity.getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, Constants.BAIDU_API_KEY);
    }

    /**
     * 开启定位服务
     */
    private void location() {
        Constants.LOCATION_LISTENER = new MyLocationListener();
        Constants.LOCATION_CLIENT = new LocationClient(zhiddActivity.getApplicationContext());
        Constants.LOCATION_CLIENT.registerLocationListener(Constants.LOCATION_LISTENER);
        Constants.LOCATION_CLIENT.setLocOption(initLocation());
        if (!Constants.LOCATION_CLIENT.isStarted()) {
            Constants.LOCATION_CLIENT.start();
        }
    }

    private LocationClientOption initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(true);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        return option;
    }

    private void uploadUserDevice() {
        if (Constants.LOGIN_USER == null) {
            return;
        }
        if (systemInof != null) {
            final String brand = systemInof.get("manufacturer");
            final String model = systemInof.get("model");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    Map<String, String> param = new HashMap<>();
                    param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                    param.put("imsi", imsi == null ? "" : imsi);
                    param.put("imei", imei == null ? "" : imei);
                    param.put("brand", brand == null ? "" : brand);
                    param.put("model", model == null ? "" : model);
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/uploadDeviceInfo", param, zhiddActivity);
                }
            }).start();
        }
    }

    private void showWaitDialog() {
        if (!zhiddActivity.isFinishing()) {
            waitDialog = new Dialog(zhiddActivity, R.style.DialogStyle);
            LayoutInflater layoutInflater = (LayoutInflater) zhiddActivity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View waitView = layoutInflater.inflate(R.layout.loading_dialog, null);
            WindowManager.LayoutParams params = new WindowManager
                    .LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            params.alpha = 0.0F;
            waitDialog.addContentView(waitView, params);
            waitDialog.show();
        }
    }

    protected void closeWaitDialog() {
        if (null != waitDialog) {
            waitDialog.cancel();
            waitDialog = null;
        }
    }
}


